<!DOCTYPE html>
<html class="x-admin-sm">

<head>
    <meta charset="UTF-8">
    <title>PicBed admin</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <link rel="stylesheet" href="../css/font.css">
    <link rel="stylesheet" href="../css/xadmin.css">
    <script src="../js/jquery.min.js"></script>
    <script src="../lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="../js/xadmin.js"></script>
    <script src="../js/common.js"></script>
    <!--[if lt IE 9]>
          <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
          <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
</head>

<body>
    <div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="">首页</a>
            <a href="">用户管理</a>
            <a>
                <cite>用户列表</cite></a>
        </span>
        <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
            onclick="location.reload()" title="刷新">
            <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
    </div>
    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-body ">
                        <form class="layui-form layui-col-space5" lay-filter="search">
                            <!-- <div class="layui-inline layui-show-xs-block">
                                <input class="layui-input" autocomplete="off" placeholder="开始日" name="start" id="start">
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <input class="layui-input" autocomplete="off" placeholder="截止日" name="end" id="end">
                            </div> -->
                            <div class="layui-inline layui-show-xs-block">
                                <input type="text" name="keywords" placeholder="用户名/手机号/邮箱/地区" autocomplete="off"
                                    class="layui-input">
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <select name="status">
                                    <option value="0">-- 请选择状态 --</option>
                                    <option value="0">全部</option>
                                    <option value="1">正常</option>
                                    <option value="2">禁用</option>
                                </select>
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <a class="layui-btn" id="search">
                                    <i class="layui-icon">&#xe615;</i>
                                    搜索
                                </a>
                            </div>
                        </form>
                    </div>
                    <div class="layui-card-header">
                        <button class="layui-btn layui-btn-danger" onclick="delAll()"><i
                                class="layui-icon"></i>批量删除</button>
                        <!-- <button class="layui-btn" onclick="add_admin()"><i class="layui-icon"></i>添加</button> -->
                    </div>
                    <div class="layui-card-body layui-table-body layui-table-main">
                        <table class="layui-table layui-form" lay-size="sm">
                            <thead>
                                <tr>
                                    <th>
                                        <input type="checkbox" lay-filter="checkall" name="" lay-skin="primary">
                                    </th>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>手机号</th>
                                    <th>邮箱</th>
                                    <th>剩余空间</th>
                                    <th>状态</th>
                                    <th>添加时间</th>
                                    <th>更新时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="table-users">

                            </tbody>
                        </table>
                    </div>
                    <div class="layui-card-body ">
                        <div class="page">
                            <div id="users-page">
                                <!-- 分页容器 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
    var laypage = null,
        form = null;
    layui.use(['laydate', 'form', 'laypage'], function () {
        var laydate = layui.laydate;

        // 赋值全局 form 对象
        form = layui.form;
        // 赋值全局分页器
        laypage = layui.laypage;

        request('/userlist', render_table, 1, 10);

        // //执行一个laydate实例
        // laydate.render({
        //     elem: '#start' //指定元素
        // });

        // //执行一个laydate实例
        // laydate.render({
        //     elem: '#end' //指定元素
        // });

        // 监听全选
        form.on('checkbox(checkall)', function (data) {

            if (data.elem.checked) {
                $('tbody input').prop('checked', true);
            } else {
                $('tbody input').prop('checked', false);
            }
            form.render('checkbox');
        });
    });


    /**
     * @name: request
     * @msg: 获取并渲染列表数据
     * @param string url 请求地址（从模块开始）
     * @param function func 要调用的函数
     * @param integer curr 当前页码数
     * @param integer limit 每一页限制数据条数
     * @param jsonObject data 请求要传的数据
     * @return: 
     */
    function request(url, func, curr, limit, data = {}) {
        $.ajax({
            url: window.config.api_url + url + '?page=' + curr + '&limit=' + limit,
            method: 'get',
            dataType: 'json',
            processData: true,
            cache: false,
            data: data,
            headers: {
                token: window.config.token,
                rtime: window.func.getTime()
            },
            success: function (res) {
                func(res, curr, limit);
            },
            error: function () {
                window.func.error();
            }
        });
    }

    // 渲染表格
    var render_table = function (res, curr, limit) {
        if (!res.data.all) {
            window.func.nodata('table-users', 11, res.code);
            form.render();
            return null;
        }

        var status = {
            '1': '正常',
            '2': '禁用'
        };


        var str = '';
        var data = res.data;
        var len = data.list.length;

        for (var i = 0; i < len; i++) {
            var created_at = window.func.date('Y-m-d H:i:s', data.list[i].created_at);
            var updated_at = window.func.date('Y-m-d H:i:s', data.list[i].updated_at);
            if (data.list[i].status == 1) {
                var a_tag =
                    `<a onclick="users_stop(this,${data.list[i].id})" href="javascript:;"  title="禁用"><i class="layui-icon">&#xe601;</i></a>`;
            } else if (data.list[i].status == 2) {
                var a_tag =
                    `<a onclick="users_stop(this,${data.list[i].id})" href="javascript:;"  title="启用"><i class="layui-icon">&#xe62f;</i></a>`;
            } else {
                var a_tag = '';
            }
            str += `<tr>
                    <td>
                      <input type="checkbox" name="id" value="${data.list[i].id}" lay-skin="primary">
                    </td>
                    <td>${data.list[i].id}</td>
                    <td>${data.list[i].username}</td>
                    <td>${data.list[i].phone ? data.list[i].phone : '--'}</td>
                    <td>${data.list[i].email ? data.list[i].email : '--'}</td>
                    <td>${data.list[i].used_spaces} / ${data.list[i].spaces}</td>
                    <td class="td-status">${status[data.list[i].status]}</td>
                    <td>${created_at}</td>
                    <td>${updated_at}</td>
                    <td class="td-manage">
                      ${a_tag}
                      <a title="调整存储空间" onclick="reset_spaces(${data.list[i].id})" href="javascript:;"><i class="layui-icon">&#xe714;</i></a>
                      <a title="删除" onclick="users_del(this,${data.list[i].id})" href="javascript:;">
                        <i class="layui-icon">&#xe640;</i>
                      </a>
                    </td>
                  </tr>`;
        }
        $('#table-users').html(str);
        form.render();

        //执行一个laypage实例
        laypage.render({
            elem: 'users-page', //注意，这里是 ID，不用加 # 号
            count: data.all, //数据总数，从服务端得到
            curr: curr, // 当前页
            limit: limit, // 每页显示条数
            limits: [5, 10, 20, 30, 40, 50], // 每页限制条数选项
            layout: ['count', 'prev', 'page', 'next', 'limit'], // 排版
            jump: function (obj, first) {
                //obj包含了当前分页的所有参数，比如：
                // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                // console.log(obj.limit); //得到每页显示的条数

                //首次不执行
                if (!first) {
                    //do something
                    request('index', render_table, obj.curr, obj.limit);
                }
            }
        });
    }

    /* 搜索 */
    $('#search').click(function () {
        var data = form.val('search');
        request('/userlist', render_table, 1, 10, data);
    });

    /*厂商用户-禁用*/
    function users_stop(obj, id) {
        if ($(obj).attr('title') == '启用') {
            var status = 1,
                title = '禁用',
                icon = '&#xe601;',
                status_str = '正常',
                tip = '启用',
                method = '/lock',
                type = 1,
                class_name = '';
        } else if ($(obj).attr('title') == '禁用') {
            var status = 2,
                title = '启用',
                icon = '&#xe62f;',
                status_str = '禁用',
                tip = '禁用',
                method = '/lock',
                type = 2,
                class_name = '';
        }
        layer.confirm('确认要' + tip + '吗？', function (index) {
            $.ajax({
                url: window.config.api_url + method,
                method: 'post',
                data: {
                    status: status,
                    id: id,
                    type: type
                },
                dataType: 'json',
                processData: true,
                cache: false,
                headers: {
                    token: window.config.token,
                    rtime: window.func.getTime()
                },
                success: function (res) {
                    if (res.code == 0) {
                        $(obj).attr('title', title)
                        $(obj).find('i').html(icon);
                        $(obj).parents("tr").find(".td-status").html(status_str);
                        if (class_name) {
                            $(obj).parents('td').find('.' + class_name).remove();
                        }
                        layer.msg('已' + tip, {
                            icon: 6,
                            time: 1000
                        });
                    } else {
                        layer.msg(res.msg, {
                            icon: 5,
                            time: 1000
                        });
                    }
                },
                error: function () {
                    window.func.error();
                }
            });
        });
    }



    function reset_spaces(id) {
        layer.open({
            title: '调整用户存储空间',
            type: 0,
            shadeClose: true,
            content: '<input id="user-spaces" value="" class="layui-input" placeholder="请输入存储大小，单位：字节">',
            yes: function (index, layero) {
                var spaces = $('#user-spaces').val();
                $.ajax({
                    url: window.config.api_url + '/resetspaces',
                    method: 'post',
                    data: { id: id, spaces: spaces },
                    dataType: 'json',
                    processData: true,
                    cache: false,
                    headers: { token: window.config.token, rtime: window.func.getTime() },
                    success: function (res) {
                        if (res.code == 0) {
                            var icon = 1;
                        } else {
                            var icon = 2;
                        }
                        layer.msg(res.msg, { time: 1000, icon: icon });
                        layer.close(index);
                        window.location.reload();
                    },
                    fail: function () {
                        window.func.error();
                    }
                });
            }
        });
    }


    /*用户-删除*/
    function users_del(obj, id) {
        layer.confirm('确认要删除吗？', function (index) {
            //发异步删除数据
            $.ajax({
                url: window.config.api_url + '/userdelete',
                method: 'post',
                data: {
                    id: id
                },
                dataType: 'json',
                processData: true,
                cache: false,
                headers: {
                    token: window.config.token,
                    rtime: window.func.getTime()
                },
                success: function (res) {
                    if (res.code == 0) {
                        $(obj).parents("tr").remove();
                        layer.msg('已删除!', {
                            icon: 1,
                            time: 1000
                        });
                    } else {
                        layer.msg(res.msg, {
                            icon: 2,
                            time: 1000
                        });
                    }
                },
                error: function () {
                    window.func.error();
                }
            });

        });
    }



    function delAll(argument) {
        var ids = [];

        // 获取选中的id 
        $('tbody input').each(function (index, el) {
            if ($(this).prop('checked')) {
                ids.push($(this).val())
            }
        });
        if (ids.length == 0) {
            layer.msg('id不能为空', { time: 1000, icon: 2 });
            return false;
        }
        layer.confirm('确认要删除吗？' + ids.toString(), function (index) {
            //捉到所有被选中的，发异步进行删除
            $.ajax({
                url: window.config.api_url + '/userdelete',
                method: 'post',
                data: {
                    id: ids
                },
                dataType: 'json',
                processData: true,
                cache: false,
                headers: {
                    token: window.config.token,
                    rtime: window.func.getTime()
                },
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 1000
                        });
                        $(".layui-form-checked").not('.header').parents('tr').remove();
                    } else {
                        layer.msg(res.msg, {
                            icon: 2,
                            time: 1000
                        });
                    }
                },
                error: function () {
                    window.func.error();
                }
            });
        });
    }
</script>

</html>